<template id="comment">
  <!--评论框-->
  <a-textarea
    id="commentTextarea"
    v-model:model-value="commentValue"
    style="height: 18vh"
    placeholder="善于结善缘，恶语伤人心"
    :max-length="1024"
    allow-clear
    show-word-limit
  />
  <div class="commentBtn">
    <a-button type="primary" @click="sendComment">发送</a-button>
  </div>

  <!--评论-->
  <a-scrollbar style="height: 48vh; overflow: auto">
    <div
      v-for="(comment, index) in parentComments"
      :key="comment.id"
      style="overflow: auto"
    >
      <!-- 一级评论 -->
      <a-comment
        :author="comment.userVO.userName"
        :avatar="
          comment.userVO.userAvatar == null
            ? 'http://hoj.h1234.top/img/logo.b5581132.svg'
            : comment.userVO.userAvatar
        "
        :content="comment.content"
        :datetime="dayjs(comment.createTime).format('YYYY-MM-DD HH:mm:ss')"
      >
        <template #actions>
          <span
            class="action"
            @click="replyComment(comment.id, comment.userVO.userName)"
          >
            <IconMessage /> 回复
          </span>
          <span
            style="cursor: pointer"
            @click="comment.isOpenFlag = !comment.isOpenFlag"
          >
            - {{ comment.isOpenFlag ? "收起" : "展开" }}
            {{ comment.childComment?.length }} 条评论
            <IconUp v-if="comment.isOpenFlag" />
            <IconDown v-else />
          </span>
        </template>
        <!-- 二级评论 -->
        <div v-show="comment.isOpenFlag" v-for="child in comment.childComment">
          <a-comment
            :author="child.userVO.userName"
            :avatar="
              child.userVO.userAvatar == null
                ? 'http://hoj.h1234.top/img/logo.b5581132.svg'
                : child.userVO.userAvatar
            "
            :content="child.content"
            :datetime="dayjs(child.createTime).format('YYYY-MM-DD HH:mm:ss')"
          >
            <template #actions>
              <span
                class="action"
                @click="replyComment(comment.id, child.userVO.userName)"
              >
                <IconMessage /> 回复
              </span>
            </template>
          </a-comment>
        </div>
      </a-comment>
    </div>
  </a-scrollbar>
</template>

<script setup lang="ts">
import { inject, ref, watchEffect } from "vue";
import dayjs from "dayjs";
import { QuestionControllerService } from "../../generated";
import { Message } from "@arco-design/web-vue";

/**
 * 定义属性类型
 */
interface Props {
  commentList: any;
  loadData: () => void;
}

/**
 * 定义属性默认值
 */
const props = withDefaults(defineProps<Props>(), {
  commentList: () => [],
  loadData: () => {},
});

// 拆分一级、二级评论
const parentComments: any = ref([]);
const childComments: any = ref([]);
const separateComments = () => {
  parentComments.value = [];
  childComments.value = [];
  for (const comment of props.commentList) {
    if (comment.parentCommentId === null) {
      // 一级评论
      parentComments.value.push(comment);
    } else {
      // 二级评论
      childComments.value.push(comment);
    }
  }
};

/**
 * 获取评论树（父评论下的子评论）
 */
const getCommentTree = () => {
  parentComments.value.forEach((item: any) => {
    item.childComment = childComments.value.filter((childComment: any) => {
      return childComment.parentCommentId == item.id;
    });
  });
};

// 接收父组件传递过来的题目id
const questionId: any = inject("questionId");

// 评论值
const commentValue: any = ref();

// 父评论id
const parentCommentId: any = ref(null);

/**
 * 发送评论
 */
const sendComment = async () => {
  // 防止点击了回复，获取到了父级id之后又把回复前的@删除造成的评论变回复
  if (!commentValue.value.startsWith("@")) {
    parentCommentId.value = null;
  }
  const res = await QuestionControllerService.addCommentUsingPost({
    questionId,
    content: commentValue.value,
    parentCommentId: parentCommentId.value,
  });
  if (res.code === 0) {
    // 重新加载数据
    props.loadData();
    // 清空输入域
    commentValue.value = "";
    Message.success("评论成功");
  } else {
    Message.error("评论失败");
  }
};

/**
 * 回复
 */
const replyComment = (commentId: any, userName: string) => {
  commentValue.value = "@" + userName + " ";
  parentCommentId.value = commentId;
  // 使输入框获取焦点
  document.getElementsByClassName("arco-textarea")[0]?.focus();
};

watchEffect(() => {
  separateComments();
  getCommentTree();
});
</script>

<style scoped>
.action {
  display: inline-block;
  padding: 0 4px;
  color: var(--color-text-1);
  line-height: 24px;
  background: transparent;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.1s ease;
}

.action:hover {
  background: var(--color-fill-3);
}

/*评论按钮*/
.commentBtn {
  display: flex;
  justify-content: right;
}
</style>